<?php

namespace App\Exceptions;

use Dingo\Api\Contract\Debug\ExceptionHandler;
use Dingo\Api\Exception\Handler as DingoHandler;
use Dingo\Api\Exception;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class DingoExceptionHandler extends DingoHandler implements ExceptionHandler
{
    public function handle($exception)
    {
        if ($exception instanceof Exception\RateLimitExceededException) {
            return response([
                'code' => 500,
                'status_code' => -1,
                'message' => '当前请求太过频繁',
            ])->withHeaders($exception->getHeaders());
        }
        if ($exception instanceof NotFoundHttpException) {
            Log::error($exception->getMessage());
            return response([
                'code' => 404,
                'status_code' => -1,
                'message' => '接口请求有误',
            ], 404);
        }
        if (
            $exception instanceof ServiceException ||
            $exception instanceof ApiException
        ) {
            if (config('app.debug')) {
                return response(get_exception($exception));
            }
            return response([
                'status_code' => 402,
                'message' => $exception->getMessage(),
                'code' => $exception->getCode(),
            ], 500);
        }
        if ($exception instanceof \Exception) {
            Log::error($exception->getMessage());
            return response([
                'code' => 500,
                'status_code' => -1,
//                'message' => '请求有误！',
                'message' => $exception->getMessage(),
            ], 500);
        }
         return parent::handle($exception);
    }
}

